﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using ConfExpert.Utility.Grid;
using ConfExpert.Utility.Peripheral;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraReports.UI;
using DevTeamIT;
using Extensions;
using ITaskManager.Datasets;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using DevTeam;

namespace ConfExpert.Forms.IT
{
    public partial class EnvanterEkle : XForm
    {
        public EnvanterEkle()
        {
            InitializeComponent();
        }

        private void EnvanterEkle_Load(object sender, EventArgs e)
        {
            this.Text = "Envanter";
            gvEnvanter.Init("IT_GetEnvanter", Session.SirketId, Session.CurrentUser.UserId);
            gvEnvanter.Columns["IT_LokasyonId"].ColumnEdit = RepositoryManager.riEL;
            gvEnvanter.Columns["IT_AlanId"].ColumnEdit = RepositoryManager.riEA;
            gvEnvanter.Columns["IT_EnvanterCesitId"].ColumnEdit = RepositoryManager.riEC;
            //gvEnvanter.Columns["IT_CihazTipiId"].ColumnEdit = RepositoryManager.riCT;
            //gvEnvanter.Columns["YaziciTipi"].ColumnEdit = RepositoryManager.riYaziciTipi;
            //gvEnvanter.Columns["BaglantiTipi"].ColumnEdit = RepositoryManager.riBaglantiTipi;
            //gvEnvanter.Columns["KagitBoyutu"].ColumnEdit = RepositoryManager.riKagitBoyutu;
            gvEnvanter.SetCaptions("IT_AlanId:Alan", "IT_LokasyonId:Lokasyon", "IT_EnvanterId:#", "IT_EnvanterCesitId:Tür");
            gvEnvanter.SetIdentity("IT_EnvanterId");
            gvEnvanter.DataTable().SetPK("IT_EnvanterId");

            gvEnvanter.Columns["UserId"].OptionsColumn.AllowEdit = true;
            gvEnvanter.Columns["UserId"].ColumnEdit = RI(Rp.V_User0);
            gvEnvanter.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;
            gvEnvanter.MakeColumnInvisible("IT_FaturaLinesId", "InsertedOn", "Model", "Yazici",
            "BaglantiTipi", "Deleted", "DkBaskiHizi", "GarantiDestek", "IMEI", "IT_CihazTipiId", "IT_FaturaLinesId", "KagitBoyutu", "KartusTonerKodu", "OfisUyg2", "OrtBaskiKapasitesi", "OtherUyg", "SatinAlmaTarihi", "SeriNo", "UrunKodu", "UzatilmisGarantiAnt", "YaziciTipi");

            //gvEnvanter.MakeColumnsReadOnly("EnvanterKodu");
            gvEnvanter.Columns["IT_EnvanterId"].ColumnEdit = null;
            gvEnvanter.RowCellStyle += gvEnvanter_RowCellStyle;
            btnKaydet.ItemClick += btnKaydet_ItemClick;
            this.FormClosing += EnvanterEkle_FormClosing;

            int ndx = 0;
            DataSet d = ExecuteDataSet("GetDistinctValues", "Env");
            foreach (string col in "IsletimSistemi,BilgisayarMarka,Model,Islemci,GHz,RAM,HDD,Yazici,AntiVirüs,RDP,OfisUyg1".Split(",".ToCharArray()))
            {
                GridColumn colUrun = gvEnvanter.Columns[col];
                colUrun.ColumnEdit = GetIntellisensedRI(d.Tables[ndx]);
                ((RepositoryItemGridLookUpEdit)colUrun.ColumnEdit).ProcessNewValue -= ri_NewValue;
                ((RepositoryItemGridLookUpEdit)colUrun.ColumnEdit).ProcessNewValue += ri_NewValue;
                ++ndx;
            }

            riHyperLink.SingleClick = false;
            gvEnvanter.Columns["DosyaId"].ColumnEdit = riHyperLink;
            gvEnvanter.RowCellClick += gridView1_RowCellClick;

            gvEnvanter.AddSummary();
            gvEnvanter.MoveLast();
            gvEnvanter.MakeRowVisible(gvEnvanter.FocusedRowHandle);

            GridManager gm = GridManager.GetManager(gvEnvanter);
            gm.GridMenu.AddMenu("Zimmet Formu Çıkar", ZimmetFormu_Click);

            btnTara.ItemClick += btnTara_ItemClick;
            gvEnvanter.BestFitColumns();
        }

        RepositoryItemHyperLinkEdit riHyperLink = new RepositoryItemHyperLinkEdit();

        void gvEnvanter_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {

            if (e.RowHandle > -1)
            {
                GridView view = sender as GridView;
                if (view.FocusedRowHandle == e.RowHandle)
                    e.Appearance.BackColor = System.Drawing.Color.YellowGreen;
                else
                    e.Appearance.Combine((e.RowHandle & 1) != 0 ? view.Appearance.EvenRow : view.Appearance.OddRow);

                //switch (e.Column.FieldName)
                //{
                //    case "Name":
                //        e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
                //        break;
                //}
            }

        }


        bool CodeOK()
        {
            Dictionary<string, int> dict = new Dictionary<string, int>();
            foreach (DataRow r in gvEnvanter.DataTable().Rows)
            {
                string EnvanterKodu = r["EnvanterKodu"].ToStr();
                if (dict.ContainsKey(EnvanterKodu))
                    dict[EnvanterKodu]++;
                else
                    dict.Add(EnvanterKodu, 1);
            }

            List<string> lst = new List<string>();
            foreach (KeyValuePair<string, int> pr in dict)
                if (pr.Value > 1)
                    lst.Add(pr.Key);

            if (lst.Count > 0)
            {
                XtraMessageBox.Show("Aşağıdaki Envanter kodları mükerrer. Düzeltip tekrar deneyin." + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, lst.ToArray()));
                return false;
            }

            return true;
        }

        private void btnKaydet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvEnvanter.EndEdit();
            string EnvanterKodu = string.Empty;
            if (gvEnvanter.GetFocusedDataRow() != null)
                EnvanterKodu = gvEnvanter.GetFocusedDataRow()["EnvanterKodu"].ToStr();

            if (!CodeOK())
                return;

            gvEnvanter.Update("", "IT_Envanter");
            gvEnvanter.VeriyiGuncelle("IT_GetEnvanter", Session.SirketId, Session.CurrentUser.UserId);

            gvEnvanter.FocusedRowHandle = gvEnvanter.LocateByDisplayText(0, gvEnvanter.Columns["EnvanterKodu"], EnvanterKodu);
            gvEnvanter.MakeRowVisible(gvEnvanter.FocusedRowHandle);
            gvEnvanter.BestFitColumns();
        }

        private void EnvanterEkle_FormClosing(object sender, FormClosingEventArgs e)
        {
            gvEnvanter.EndEdit();

            if (gvEnvanter.Dataset().HasChanges())
                if (XtraMessageBox.Show("Değişiklikleri kaydetmemiş olabilirsiniz; çıkmak istediğinize emin misiniz?", "Uyarı", MessageBoxButtons.YesNo) == DialogResult.No)
                    e.Cancel = true;
                else
                    e.Cancel = false;
        }

        private void ZimmetFormu_Click(object sender, EventArgs e)
        {
            int UserId = gvEnvanter.GetFocusedRowCellValue("UserId").ToInt();
            xrZimmetFormu xr = new xrZimmetFormu(UserId);
            xr.ShowPreview();
        }

        void btnTara_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                gvEnvanter.EndEdit();

                this.Cursor = Cursors.WaitCursor;

                //Scanner scanner = new Scanner();
                Image i2 = Scanner.ScanDoc();    //kumaş için sabitlendi

                if (i2 != null)
                {
                    int UserId = gvEnvanter.GetFocusedDataRow()["UserId"].ToInt();

                    ds.xBuffer.Clear();

                    MyData.xBufferRow xpr = ds.xBuffer.NewxBufferRow();
                    xpr.intVal = UserId;
                    xpr.photoVal = ConvertImageToByteArray(i2, System.Drawing.Imaging.ImageFormat.Png);
                    ds.xBuffer.AddxBufferRow(xpr);

                    gvEnvanter.VeriyiGuncelle(false, "UpdxBuffer", ds.xBuffer, 7);
                    GC.Collect();
                    Notify("Kaydedildi");

                    //gvRoll.Columns["Photo"].Width = 34;
                }
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

        }

        void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.RowHandle < 0)
                return;

            if (e.Column.FieldName == "DosyaId")
            {
                Cursor.Current = Cursors.WaitCursor;
                DataRow dr = gvEnvanter.GetDataRow(e.RowHandle);
                int UserId = dr["UserId"].ToInt();
                DataTable t = Session.DataManager.ExecuteDataTable("IT_GetZimmetGoster", UserId);

                if (t.Rows.Count > 0)
                {
                    byte[] bytes = (byte[])t.Rows[0]["BLOB"];
                    string FileName = t.Rows[0]["DosyaAdi"].ToStr()+".PNG";

                    FileManager.RunTempFile(FileName, bytes);
                }
                this.Cursor = Cursors.Default;
            }
        }

        public string ByteArrayToFile3(string filePath, byte[] content)
        {
            string FullPath = /*System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache) + "\\" +*/ filePath;
            using (FileStream fs = new FileStream(FullPath, FileMode.Create, FileAccess.Write))
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                bw.Write(content);
                bw.Flush();
            }


            return FullPath;
        }

        void ExecQueryTV(string SP, params object[] p)
        {
            using (SqlConnection sqlConn = new SqlConnection(Session.DataManager.ConnectionString))
            {
                sqlConn.Open();
                SqlCommand sqlCmd = sqlConn.CreateCommand();
                sqlCmd.CommandText = SP;
                sqlCmd.CommandType = CommandType.StoredProcedure;
                SqlParameter[] parameters = new SqlParameter[2];
                parameters[0] = new SqlParameter("@tbl", SqlDbType.Structured);
                parameters[0].Value = p[0];
                parameters[1] = new SqlParameter("@TurId", SqlDbType.Int);
                parameters[1].Value = p[1];
                sqlCmd.Parameters.AddRange(parameters);
                sqlCmd.ExecuteNonQuery();
            }
        }

    }
}